import React, { useState, useEffect } from 'react';
import {
  Button,
  Table,
  Space,
  Tag,
  message,
  Modal,
  Form,
  Input,
  Select,
  Popconfirm,
  Avatar,
  Tabs,
  Checkbox
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  PlusOutlined,
  SearchOutlined,
  LockOutlined
} from '@ant-design/icons';
import { getUserAvatarPlaceholder } from '../../utils/imageUtils';
import './UserManage.css';
import { useRequest } from 'ahooks';
import { getUsers, getRoles, deleteUsers, updateUsers } from '../../api/dashboard';


const { Option } = Select;
const { TabPane } = Tabs;

const UserManage = () => {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('users');
  const [roleVisible, setRoleVisible] = useState(false);
  const [roleConfirmLoading, setRoleConfirmLoading] = useState(false);
  const [roleForm] = Form.useForm();
  const [editingRoleId, setEditingRoleId] = useState(null);


  const { runAsync: fetchUsers } = useRequest(getUsers, { manual: true });
  const { runAsync: fetchRole } = useRequest(getRoles, { manual: true });
  const { runAsync: updateUser } = useRequest(updateUsers, { manual: true });
  const { runAsync: deleteUser } = useRequest(deleteUsers, { manual: true });


  const fetchData = async () => {
    const id = localStorage.getItem('adminUser').id || 1;
    const storedUsers = await fetchUsers({ params: { id: id } });
    setUsers(storedUsers);
    const role = await fetchRole({ params: { id: id } });
    setRoles(role);
  }

  // 获取用户和角色数据
  useEffect(() => {
    setLoading(true);
    fetchData();
    setLoading(false);
  }, []);

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 用户表格列定义
  const userColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text) => (
        <Space>
          <Avatar icon={<UserOutlined />} size="small" src={getUserAvatarPlaceholder(text, '40x40')} />
          <span>{text}</span>
        </Space>
      ),
      filteredValue: [searchText],
      onFilter: (value, record) =>
        (record.username?.toLowerCase().includes(value.toLowerCase()) || '') ||
        (record.email?.toLowerCase().includes(value.toLowerCase()) || '')
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        <Tag color={
          role === 'admin' ? 'red' :
            role === 'manager' ? 'blue' : 'green'
        }>
          {role}
        </Tag>
      ),
      filters: roles.map(role => ({ text: role.name, value: role.name })),
      onFilter: (value, record) => record.role === value
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '正常' : '禁用'}
        </Tag>
      ),
      filters: [
        { text: '正常', value: 'active' },
        { text: '禁用', value: 'inactive' }
      ],
      onFilter: (value, record) => record.status === value
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text) => formatDate(text),
      sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime)
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      render: (text) => formatDate(text),
      sorter: (a, b) => new Date(a.lastLoginTime) - new Date(b.lastLoginTime)
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 角色表格列定义
  const roleColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions) => (
        <div>
          {permissions.map(permission => (
            <Tag key={permission} color="blue">
              {permission}
            </Tag>
          ))}
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEditRole(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDeleteRole(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              size="small"
              disabled={record.name === 'admin' || record.name === 'manager'}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
  };

  // 添加用户
  const handleAddUser = () => {
    form.resetFields();
    setEditingId(null);
    form.setFieldsValue({
      status: 'active',
      role: 'user'
    });
    setVisible(true);
  };

  // 编辑用户
  const handleEditUser = (record) => {
    setEditingId(record.id);
    form.setFieldsValue({
      username: record.username,
      email: record.email,
      phone: record.phone,
      role: record.role,
      status: record.status
    });
    setVisible(true);
  };

  // 删除用户
  const handleDeleteUser = async (id) => {
    if (id === 1) {
      message.error('不能删除管理员账号');
      return;
    }
    try {
      const updatedUsers = await deleteUser({ params: { id } });
      setUsers(updatedUsers);
      message.success('用户删除成功');
    } catch (e) {
      message.error('用户删除失败');
    }
  };

  // 编辑角色
  const handleEditRole = (record) => {
    setEditingRoleId(record.id);
    roleForm.setFieldsValue({
      name: record.name,
      description: record.description,
      permissions: record.permissions
    });
    setRoleVisible(true);
  };

  // 删除角色
  const handleDeleteRole = (id) => {
    const roleToDelete = roles.find(role => role.id === id);

    if (roleToDelete.name === 'admin' || roleToDelete.name === 'manager') {
      message.error('不能删除系统预设角色');
      return;
    }

    // 检查是否有用户使用该角色
    const hasUsers = users.some(user => user.role === roleToDelete.name);

    if (hasUsers) {
      message.error('该角色下还有用户，不能删除');
      return;
    }

    const updatedRoles = roles.filter(role => role.id !== id);
    setRoles(updatedRoles);
    localStorage.setItem('roles', JSON.stringify(updatedRoles));
    message.success('角色删除成功');
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(async values => {
        setConfirmLoading(true);

        setTimeout(async () => {
          if (editingId) {
            // 更新用户
            const updatedUsers = await updateUser([{
              id: editingId,
              ...values,
            }]);
            setUsers(updatedUsers);
            message.success('用户更新成功');
          } else {
            // 添加新用户
            const newUser = {
              ...values,
              id: Date.now(),
              createTime: new Date().toISOString(),
              lastLoginTime: null
            };
            const updatedUsers = await updateUser([newUser]);
            setUsers(updatedUsers);
            message.success('用户添加成功');
          }

          setVisible(false);
          setConfirmLoading(false);
        }, 1000);
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 处理模态框取消
  const handleCancel = () => {
    setVisible(false);
  };

  // 处理角色表单提交
  const handleRoleSubmit = () => {
    roleForm.validateFields()
      .then(async values => {
        setRoleConfirmLoading(true);

        setTimeout(() => {
          if (editingRoleId) {
            // 更新角色权限
            const updatedRoles = roles.map(role =>
              role.id === editingRoleId
                ? { ...role, ...values }
                : role
            );
            setRoles(updatedRoles);
            localStorage.setItem('roles', JSON.stringify(updatedRoles));
            message.success('角色权限更新成功');
          }

          setRoleVisible(false);
          setRoleConfirmLoading(false);
        }, 1000);
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 处理角色模态框取消
  const handleRoleCancel = () => {
    setRoleVisible(false);
  };

  // 处理标签切换
  const handleTabChange = (key) => {
    setActiveTab(key);
  };

  return (
    <div className="user-manage">
      <Tabs activeKey={activeTab} onChange={handleTabChange}>
        <TabPane tab="用户管理" key="users">
          <div className="page-header">
            <h2>用户管理</h2>
            <div className="page-header-actions">
              <Input
                placeholder="搜索用户名或邮箱"
                prefix={<SearchOutlined />}
                style={{ width: 200, marginRight: 16 }}
                allowClear
                onChange={(e) => handleSearch(e.target.value)}
              />
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddUser}
              >
                添加用户
              </Button>
            </div>
          </div>

          <Table
            columns={userColumns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </TabPane>
        <TabPane tab="角色管理" key="roles">
          <div className="page-header">
            <h2>角色管理</h2>
          </div>

          <Table
            columns={roleColumns}
            dataSource={roles}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </TabPane>
      </Tabs>

      {/* 用户表单 */}
      <Modal
        title={editingId ? "编辑用户" : "添加用户"}
        open={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        confirmLoading={confirmLoading}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
          name="userForm"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入用户名"
            />
          </Form.Item>

          {!editingId && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
              />
            </Form.Item>
          )}

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
            help={editingId ? "编辑用户时不能修改角色" : ""}
          >
            <Select
              placeholder="请选择角色"
              disabled={editingId !== null}
            >
              {roles.map(role => (
                <Option key={role.id} value={role.name}>{role.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">正常</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 角色编辑表单 */}
      <Modal
        title="编辑角色权限"
        open={roleVisible}
        onOk={handleRoleSubmit}
        onCancel={handleRoleCancel}
        confirmLoading={roleConfirmLoading}
        maskClosable={false}
      >
        <Form
          form={roleForm}
          layout="vertical"
          name="roleForm"
        >
          <Form.Item
            name="name"
            label="角色名称"
          >
            <Input disabled placeholder="角色名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="角色描述"
            rules={[{ required: true, message: '请输入角色描述' }]}
          >
            <Input.TextArea placeholder="请输入角色描述" rows={3} />
          </Form.Item>

          <Form.Item
            name="permissions"
            label="权限设置"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <Checkbox.Group
              options={[
                { label: '控制台', value: 'dashboard' },
                { label: '商品管理', value: 'products' },
                { label: '分类管理', value: 'categories' },
                { label: '订单管理', value: 'orders' },
                { label: '用户管理', value: 'users' }
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManage; 